package ui;

import server.ClientReaderThread;

import javax.swing.*;
import java.awt.*;
import java.net.Socket;
import java.util.List;

public class ChatFrame extends JFrame {
    private JTextArea chatArea;
    private JTextField inputField;
    private JButton sendButton;
    private JLabel onlineCountLabel;
    private String nickname;
    private Socket socket;

    public ChatFrame() {
        setTitle("聊天界面");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 主面板，使用BorderLayout
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 左侧聊天内容区
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane chatScrollPane = new JScrollPane(chatArea);
        mainPanel.add(chatScrollPane, BorderLayout.CENTER);

        // 右侧在线人数显示
        JPanel rightPanel = new JPanel(new BorderLayout());
        onlineCountLabel = new JLabel("在线人数: 0");
        onlineCountLabel.setHorizontalAlignment(SwingConstants.CENTER);
        rightPanel.add(onlineCountLabel, BorderLayout.NORTH);
        rightPanel.setPreferredSize(new Dimension(120, 0));
        mainPanel.add(rightPanel, BorderLayout.EAST);

        // 底部输入区，包含输入框和发送按钮
        JPanel bottomPanel = new JPanel(new BorderLayout(5, 5));
        inputField = new JTextField();
        sendButton = new JButton("发送");
        bottomPanel.add(inputField, BorderLayout.CENTER);
        bottomPanel.add(sendButton, BorderLayout.EAST);

        mainPanel.add(bottomPanel, BorderLayout.SOUTH);

        add(mainPanel);

        this.setVisible(true);



    }
    public ChatFrame(String nickname, Socket socket) {
        this();
        this.setTitle(nickname + "的聊天界面");
        this.nickname = nickname;
        this.socket = socket;
        //立即把客户端的Socket对象传给服务器端，让服务器端知道当前客户端的昵称和Socket对象
        new ClientReaderThread(socket,this).start();


    }


    public void updateOnlineUsers(List<String> onLineList) {
        // 更新在线人数显示
        String onlineCount = "在线人数: " + onLineList.size();
        onlineCountLabel.setText(onlineCount);


    }
}